package com.softa.common.sysconfig.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.softa.common.constant.Constants;
import com.softa.common.sysconfig.exception.BaseException;
import com.softa.common.sysconfig.exception.UnAuthorizedException;
import com.softa.common.sysconfig.properties.PandaCoreProperties;
import com.softa.common.sysconfig.shiro.token.KissoToken;
import com.softa.common.sysconfig.support.Result;
import com.softa.common.utils.WebUtil;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * description goes here.
 *
 * @author 杨磊
 * @date 2019/5/13 21:17
 * @since 1.0
 **/
public class MyAuthenticatingFilter extends BasicHttpAuthenticationFilter {

    private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private PandaCoreProperties pandaCoreProperties;

    public MyAuthenticatingFilter(PandaCoreProperties pandaCoreProperties){
       this.pandaCoreProperties = pandaCoreProperties;
    }

    /**
     * 判断用户是否想要登入
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(AUTHORIZATION_HEADER);
        //暂时返回true
        return true;
    }

    /**
     *
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String path = httpServletRequest.getServletPath();
        //不需要拦截的url
        List<String> annonFilter = pandaCoreProperties.getShiroAnonFilter();
        boolean isflag = WebUtil.isAnnoRequest(path, annonFilter);
        if(isflag){
            return true;
        }
        SSOToken ssoToken = SSOHelper.getSSOToken(httpServletRequest);
        if(null != ssoToken){
            KissoToken token = new KissoToken(ssoToken.getId());
            // 提交给realm进行登入，如果错误他会抛出异常并被捕获
            getSubject(request, response).login(token);
            // 如果没有抛出异常则代表登入成功，返回true
            return true;
        }else{
            return false;
        }
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            try {
                boolean isflag = executeLogin(request, response);
                if(!isflag){
                    response401(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response401(request, response);
            }
        }
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /401
     */
    private void response401(ServletRequest req, ServletResponse resp) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
            response(httpServletResponse, new UnAuthorizedException("please login"));
    }

    private void response(HttpServletResponse response, BaseException exception){
        ServletOutputStream outputStream = null;
        try{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(exception.getCode().value());
            outputStream = response.getOutputStream();
            outputStream.write(JSONObject.toJSONString(buildResult(exception)).getBytes());
        } catch (IOException e) {
            LOGGER.error("login error - response error",e.getMessage());
        }finally {
            if(null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Result buildResult(BaseException ex){
        ModelMap map = new ModelMap();
        ex.handler(map);
        String message = map.get(Constants.EXCEPTION_MSG) == null ? null : map.get(Constants.EXCEPTION_MSG).toString();
        Integer code = Integer.parseInt(map.get(Constants.EXCEPTION_CODE).toString());
        Integer msgCode = map.get(Constants.EXCEPTION_MSGCODE) == null ? null : Integer.parseInt(map.get(Constants.EXCEPTION_MSGCODE).toString());
        return new Result(code, msgCode, message);
    }

}
